package main

import (
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	fmt.Print("### 排序整数数字 ###\n\n")
	for {

		terminalInput := getInput()

		sliceSplitByComma := strings.Split(terminalInput, ",")

		UnsortedSlice := getIntSliceFromStrSlice(sliceSplitByComma)

		sortedSlice := sortIntSlice(UnsortedSlice)

		fmt.Printf("排序结果为： %v\n\n", sortedSlice)

	}
}

func getInput() (terminalInput string) {
	fmt.Print("输入多个整数（英文逗号','隔开)，输入 q 退出：")
	_, err := fmt.Scanln(&terminalInput)
	if err != nil {
		fmt.Println("扫描输入出错： ", err)
		panic("扫描输入出错")
	}
	if terminalInput == "q" {
		fmt.Println("程序即将退出...")
		os.Exit(0)
	}
	return
}

func getIntSliceFromStrSlice(strSlice []string) (intSlice []int) {
	for _, val := range strSlice {
		intDigit, err := strconv.Atoi(val)
		if err != nil {
			fmt.Println(err)
		}
		intSlice = append(intSlice, intDigit)
	}
	return
}

func sortIntSlice(s []int) (sortedSlice []int) {
	for len(s) > 0 {
		index, minNum := getMinNum(s)
		sortedSlice = append(sortedSlice, minNum)
		s = removeElementByIndex(s, index)
	}
	return
}

func removeElementByIndex(s []int, index int) []int {
	return append(s[:index], s[index+1:]...)
}

func getMinNum(s []int) (index int, minNum int) {
	minNum = s[0]
	for i := 1; i < len(s); i++ {
		if minNum > s[i] {
			index, minNum = i, s[i]
		}
	}
	return
}
